#include "config.h"

#include "ms2wgen.h"

char	*confpath = "ms2wgen.conf";

static sr_t	*sr_mod_conf;

static ECMBOOL
setup_sr_conf(sr_t *sr_conf)
{
	sr_t	*sr_duration;
	sr_t	*sr_arrival_lambda;
	sr_t	*sr_skew;
	sr_t	*sr_media_size;
	sr_t	*sr_media_length;
	sr_t	*sr_n_medias;
	sr_t	*sr_sesslen_alpha;
	sr_t	*sr_sesslen_beta;
	sr_t	*sr_interseek_mu;
	sr_t	*sr_interseek_sigma;
	sr_t	*sr_output;
	ecm_int32	l_n_medias;

	if ((sr_duration = sr_getc(sr_conf, "duration"))) {
		duration = msl_parse_duration((char *)sr_get_str(sr_duration));
		if (duration == 0) {
			ERR("duration: invalid format: %s", sr_get_str(sr_duration));
			return ECM_FALSE;
		}
	}

	if ((sr_arrival_lambda = sr_getc(sr_conf, "arrival_lambda"))) {
		arrival_lambda = sr_get_dbl(sr_arrival_lambda);
	}

	if ((sr_skew = sr_getc(sr_conf, "skew"))) {
		skew = sr_get_dbl(sr_skew);
		if (skew < 0) {
			ERR("skew: invalid skew value");
			return ECM_FALSE;
		}
	}

	if ((sr_sesslen_alpha = sr_getc(sr_conf, "sesslen_alpha"))) {
		sesslen_alpha = sr_get_dbl(sr_sesslen_alpha);
	}
	if ((sr_sesslen_beta = sr_getc(sr_conf, "sesslen_beta"))) {
		sesslen_beta = sr_get_dbl(sr_sesslen_beta);
	}

	if ((sr_interseek_mu = sr_getc(sr_conf, "interseek_mu"))) {
		interseek_mu = sr_get_dbl(sr_interseek_mu);
	}
	if ((sr_interseek_sigma = sr_getc(sr_conf, "interseek_sigma"))) {
		interseek_sigma = sr_get_dbl(sr_interseek_sigma);
	}

	if ((sr_media_length = sr_getc(sr_conf, "media_length"))) {
		media_length = sr_get_int(sr_media_length);
	}
	if ((sr_media_size = sr_getc(sr_conf, "media_size"))) {
		media_size = sr_get_int(sr_media_size);
	}

	if ((sr_n_medias = sr_getc(sr_conf, "n_medias"))) {
		l_n_medias = sr_get_int(sr_n_medias);
		if (l_n_medias <= 0) {
			ERR("n_medias: invalid number of media");
			return ECM_FALSE;
		}
		n_medias = l_n_medias;
	}

	if ((sr_output = sr_getc(sr_conf, "output"))) {
		output = ecm_strdup(sr_get_str(sr_output));
	}

	return ECM_TRUE;
}

static sr_t *
load_sr_conf(const char *confpath)
{
	sr_t	*sr;
	char	*buf;
	ecm_size_t	size;
	int	fd;

	fd = ecm_open(confpath, ECM_O_RDONLY);
	if (fd < 0)
		return NULL;
	if (!ecm_filesize(fd, &size)) {
		ecm_close(fd);
		return NULL;
	}
	buf = (char *)ecm_malloc(size + 1);
	if (buf == NULL) {
		ecm_close(fd);
		return NULL;
	}
	buf[size] = '\0';

	if (!ecm_read(fd, buf, &size)) {
		ecm_close(fd);
		return NULL;
	}
	sr = sr_asr_scan(buf);
	ecm_close(fd);

	return sr;
}

sr_t *
get_mod_sr_conf(const char *modname)
{
	return sr_getc(sr_mod_conf, modname);
}

ECMBOOL
init_wgenconf(void)
{
	sr_t	*sr_conf;
	ECMBOOL	res;

	if (ecm_empty_str(confpath) || !ecm_access(confpath, ECM_R_OK))
		return ECM_TRUE;

	sr_conf = load_sr_conf(confpath);

	if (sr_conf == NULL) {
		ERR("%s: cannot load configuration", confpath);
		return ECM_FALSE;
	}

	res = setup_sr_conf(sr_conf);
	sr_mod_conf = sr_dup(sr_getc(sr_conf, "modules"));

	sr_free(sr_conf);

	return res;
}
